package com.zzl.gulimall.product.config;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Title: MessageResourceExtension.class<br>
 * Description: <br>
 * @author zzl
 */
@Component("messageSource")
public class MessageResourceExtension extends ResourceBundleMessageSource implements ResourceLoaderAware {

    private final static Logger logger = LoggerFactory.getLogger(MessageResourceExtension.class);

    /**
     * 指定的国际化文件目录
     */
    @Value(value = "${spring.messages.baseFolder:i18n}")
    private String baseFolder;

//    /**
//     * 父MessageSource指定的国际化文件
//     */
//    @Value(value = "${spring.messages.basename:message}")
//    private String basename;

    @PostConstruct
    public void init() {
        logger.info("================= init MessageResourceExtension... ===============");
        if (!StringUtils.isEmpty(baseFolder)) {
            try {
                this.setBasenames(getAllBaseNames(baseFolder));
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        this.setDefaultEncoding("UTF-8");
    }

    /**
     * 获取文件夹下所有的国际化文件名
     *
     * @param folderName 文件名
     * @return
     * @throws IOException
     */
    private String[] getAllBaseNames(String folderName) throws IOException {
        Resource[] classResources = resourcePatternResolver.getResources(getLocationPattern());
        List<String> baseNames = new ArrayList<>();
        if (classResources != null) {
            for (Resource resource : classResources) {
                String name = resource.getFilename();
                String rName = folderName + File.separator + getI18FileName(name);
                if (!baseNames.contains(rName)) {
                    baseNames.add(rName);
                }
            }
        }
        return baseNames.toArray(new String[baseNames.size()]);
    }

    /**
     * 把普通文件名转换成国际化文件名
     *
     * @param filename
     * @return
     */
    private String getI18FileName(String filename) {
        filename = filename.replace(".properties", "");
        for (int i = 0; i < 2; i++) {
            int index = filename.lastIndexOf("_");
            if (index != -1) {
                filename = filename.substring(0, index);
            }
        }
        return filename;
    }

    protected ResourcePatternResolver resourcePatternResolver;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
    }

    /**
     * 获取资源的路径
     *
     * @return
     */
    protected String getLocationPattern() {
        return ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + ClassUtils.convertClassNameToResourcePath(baseFolder) + "/**/*.properties";
    }

}
